import type { PropType } from 'vue';

import { defineAsyncComponent, defineComponent, h, ref } from 'vue';

import { $t } from '@vben/locales';

const ElInput = defineAsyncComponent(() =>
  Promise.all([
    import('element-plus/es/components/input/index'),
    import('element-plus/es/components/input/style/css'),
  ]).then(([res]) => res.ElInput),
);
// 创建独立的 EnhancedTextarea 组件
const EnhancedTextarea = defineComponent({
  name: 'EnhancedTextarea',
  inheritAttrs: false,
  props: {
    modelValue: {
      type: [String, Number],
      default: '',
    },
    placeholder: {
      type: String,
      default: '',
    },
    resize: {
      type: String as PropType<'both' | 'horizontal' | 'none' | 'vertical'>,
      default: 'vertical',
    },
    autosize: {
      type: [Boolean, Object],
      default: () => ({ minRows: 3, maxRows: 6 }),
    },
    showWordLimit: {
      type: Boolean,
      default: true,
    },
    maxlength: {
      type: Number,
      default: undefined,
    },
  },
  emits: ['update:modelValue', 'change', 'focus', 'blur'],
  setup(props, { attrs, emit, expose }) {
    const innerRef = ref();

    const handleInput = (value: string) => {
      emit('update:modelValue', value);
    };

    const handleFocus = (event: FocusEvent) => {
      emit('focus', event);
    };

    const handleBlur = (event: FocusEvent) => {
      emit('blur', event);
    };

    expose({
      focus: () => innerRef.value?.focus?.(),
      blur: () => innerRef.value?.blur?.(),
      select: () => innerRef.value?.select?.(),
    });

    return () => {
      const placeholder =
        props.placeholder ||
        attrs.placeholder ||
        $t('ui.placeholder.textarea') ||
        '请输入内容';

      // 使用渲染函数创建组件
      return h(
        ElInput as any, // 使用类型断言避免类型检查
        {
          ref: innerRef,
          type: 'textarea',
          modelValue: props.modelValue,
          placeholder,
          resize: props.resize,
          autosize: props.autosize,
          showWordLimit: props.showWordLimit,
          maxlength: props.maxlength,
          clearable: true,
          ...attrs,
          onInput: handleInput,
          onFocus: handleFocus,
          onBlur: handleBlur,
        },
      );
    };
  },
});
export { EnhancedTextarea };
